package com.fs.console.base.utils;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fs.console.base.vo.Sort;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ACE
 * @desc 分页助手
 * @creationTime 2019-03-08 14:50
 * @projectName gps-root
 * @packageName com.fs.base.utils
 */
public class PageHeper<T> {
    private final static int FIRST_PAGE = 1;
    private final static int DEFAULT_PAGE_SIZE = 10;

    private static String PAGE = "page";
    private static String PAGE_SIZE = "rows";
    private static String SORT = "sort";
    private static String ORDER = "order";
    private static String NO_PAGE = "noPage";

    /**
     * 是否分页
     * @param request
     * @return
     */
    public static boolean isPage(HttpServletRequest request){
        Boolean flag = true;
        if(StringUtils.isNotBlank(request.getParameter(NO_PAGE))){
            flag = false;
        }
        return flag;

    }

    /**
     * @param request
     * @return
     */
    public static Page pageRequest(HttpServletRequest request, Class aClass){
        int page = FIRST_PAGE ;
        int size = DEFAULT_PAGE_SIZE ;

        if(StringUtils.isNotBlank(request.getParameter(NO_PAGE))){
            return new Page<Class>(FIRST_PAGE, Integer.MAX_VALUE);
        }

        if(StringUtils.isNotBlank(request.getParameter(PAGE))){
            page = Integer.parseInt(request.getParameter(PAGE));
        }
        if(StringUtils.isNotBlank(request.getParameter(PAGE_SIZE))){
            size = Integer.parseInt(request.getParameter(PAGE_SIZE));
        }
        return new Page(page, size);
    }

    /**
     * 返回排序对象
     * @param request
     * @return
     */
    public static Sort sort(HttpServletRequest request){
        String orderField = request.getParameter(SORT);
        String orderType = request.getParameter(ORDER);
        Sort _sort = null;
        if(StringUtils.isNotBlank(orderField)){
            List<String> field = new ArrayList<>();
            for (String s : orderField.split(",")) {
                field.add(s);
            }
            _sort = new Sort(orderType, field);
        }else{
            return null;
        }
        return _sort;

    }
}
